﻿using System.Diagnostics;
using System.Linq;
using Atha.Contracts;
using Atha.Extensions.Strings;
using RazorEngine.Templating;

namespace Atha.Languages.Razor
{
	public sealed class RazorTestRunContext : ScriptTestRunContextBase
	{
		public RazorTestRunContext(string name, string script)
			: base(name, script)
		{
		}

		protected override void OnExecute(string script, ITestRunResultBuilder testRunResultBuilder)
		{
			try
			{
				var executionCtx = new PascalCaseTestExecutionContext(testRunResultBuilder);

				RazorEngine.Razor.SetTemplateBase(typeof(RazorTemplate<>));
				RazorEngine.Razor.Parse(script, executionCtx);
			}
			catch (TemplateCompilationException templateCompilationException)
			{
				foreach (var err in templateCompilationException.Errors.Where(e => !e.IsWarning))
				{
					Debug.WriteLine("Error on Ln {0}, Col {1}: {2}".FormatWith(err.Line, err.Column, err.ErrorText));

					testRunResultBuilder.AddResult(new SyntaxErrorTestResult(err.Line, err.Column, "({0}) {1}".FormatWith(err.ErrorNumber, err.ErrorText)));
				}

				testRunResultBuilder.AddResult(new ExceptionTestResult(templateCompilationException));
			}
		}
	}
}